﻿using Sharepoint.Entities;
using TopGroup.MySharePoint.Lists;
using TopGroup.MySharePoint.Views;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using TopGroup.MySharePoint.ServiceUserGroup;
using SharePoint.Entities;
using TopGroup.MySharePoint.UserProfile;
using TopGroup.MySharePoint.DataModel;
using System.Security.Principal;
using Windows.Storage.Streams;

namespace TopGroup.MySharePoint.DataModel
{
    public class TGSharePoint
    {
        /// <summary>
        /// Retorna Noticias del sitio de SharePoint desde una lista de nombre Noticias
        /// </summary>
        /// <param name="parameters">Objeto con paramètros de conexión</param>
        /// <returns>Listado genérico de tipo TGNews</returns>
        public async Task<List<TGNews>> GetNewsTile(TGParametters parameters)
        {
            TGNews item = null;
            List<TGNews> itemsResult = new List<TGNews>();
            GetListResponse items = new GetListResponse();
            string idView = string.Empty;
            string idList = string.Empty;
            string path = string.Empty;
            try
            {

                BasicHttpBinding binding = new BasicHttpBinding();
                binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
                EndpointAddress address = new EndpointAddress(parameters.Url + "/_vti_bin/lists.asmx");
                ListsSoapClient lists = new ListsSoapClient(binding, address);
                lists.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Delegation;
                lists.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(parameters.Login, parameters.Password, parameters.Dominio);
                XDocument xmlDoc = new XDocument();
                XElement query = new XElement("Query");
                XElement viewFields = new XElement("ViewFields");
                XElement queryOptions = new XElement("QueryOptions");
                query.Value = "<Where><IsNotNull><FieldRef Name='ID' /></IsNotNull></Where>";
                queryOptions.Value = "";
                Lists.GetListResponse news = await lists.GetListAsync("Noticias");
                idList = news.Body.GetListResult.Attribute("ID").Value;


                GetListItemsResponse itemsResponse = await lists.GetListItemsAsync(idList, null, query, null, "5", queryOptions, null);

                var data = from temp in itemsResponse.Body.GetListItemsResult.Descendants().Descendants()
                           select temp;

                foreach (var itemTemp in data)
                {
                    item = new TGNews();
                    if (itemTemp.Attribute("ows_Title") != null)
                        item.Title = itemTemp.Attribute("ows_Title").Value;
                    if (itemTemp.Attribute("ows_Thumbnail") != null)
                        item.Thumbnail = itemTemp.Attribute("ows_Thumbnail").Value;
                    if (!string.IsNullOrEmpty(item.Thumbnail))
                    {
                        GetImageNews(item.Thumbnail, item.Title, parameters);
                        item.Thumbnail = parameters.AppPath + item.Title + ".png";
                    }
                    itemsResult.Add(item);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return itemsResult;
        }

        public async void GetImageNews(string thumbnail, string title, TGParametters parameters)
        {
            thumbnail = thumbnail.Replace("MThumb", "LThumb");
            BackgroundDownloader downloader = new BackgroundDownloader();
            Uri source = new Uri(thumbnail);
            StorageFile destinationFile = null;
            DownloadOperation download = null;
            ResponseInformation response = null;
            var path = Windows.Storage.ApplicationData.Current.LocalFolder;
            parameters.AppPath = path.Path + "\\";
            try
            {
                destinationFile = await path.CreateFileAsync(title + ".png", CreationCollisionOption.ReplaceExisting);
                using (IRandomAccessStream random = await destinationFile.OpenAsync(FileAccessMode.Read))
                {
                    using (Stream stream = random.AsStreamForRead())
                    {
                        downloader.ServerCredential = new Windows.Security.Credentials.PasswordCredential();
                        downloader.ServerCredential.Password = parameters.Password;
                        downloader.ServerCredential.UserName = parameters.Dominio + @"\" + parameters.Login;
                        download = downloader.CreateDownload(source, destinationFile);
                        await download.StartAsync();
                        response = download.GetResponseInformation();
                        stream.Flush();
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}
